/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.lardocelar.core.basededados;

import br.com.lardocelar.core.BaseDeDados;
import br.com.lardocelar.core.Servidor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author LeandroL
 */
public class MySql implements BaseDeDados {

    private String user;
    private String pass;

    public MySql() {

    }

    @Override
    public String getId() {
        return "0";
    }

    @Override
    public String getDriver() {
        return "com.mysql.jdbc.Driver";
    }

    @Override
    public String getUrl() {
        return "jdbc:mysql://localhost/STUDENTS";
    }

    @Override
    public String getUser() {
        return user;
    }

    @Override
    public String getPass() {
        return pass;
    }

    @Override
    public void setUser(String User) {
        user = User;
    }

    @Override
    public void setPass(String Pass) {
        pass = Pass;
    }

    @Override
    public Connection getDBConnection() {
        Connection dbConnection = null;

        try {
            Class.forName(getDriver());
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }

        try {
            dbConnection = DriverManager.getConnection(
                    getUrl(), getUser(), getPass());
            return dbConnection;
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return dbConnection;
    }

    @Override
    public List ListarTodosServidores() {
        List servidores = new LinkedList();
        String query = "SELECT id, text FROM blogs WHERE UPPER(text) LIKE ?";
        Connection dbConnection = getDBConnection();
        
        try {
            try (PreparedStatement ps = dbConnection.prepareStatement(query); ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    servidores.add(Servidor.Carregar(rs.getBytes("ipAddress"), rs.getInt("Porta")));
                }
            }
            dbConnection.close();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return servidores;
    }
}
